package cn.kimming.service.impl;

import cn.kimming.common.constant.SystemConstant;
import cn.kimming.common.exception.SystemException;
import cn.kimming.common.pojo.Employee;
import cn.kimming.common.util.DateUtil;
import cn.kimming.common.vo.EmployeeVO;
import cn.kimming.mapper.EmployeeMapper;
import cn.kimming.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 刘铭轩
 * date 2021-05-23
 */
@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Employee bo) {
        checkUsername(bo);
        bo.setPassword(SystemConstant.EMPLOYEE_DEFAULT_PASSWORD);
        bo.setEmpNumber(DateUtil.genEmpNumber());
        employeeMapper.insertSelective(bo);
    }

    @Override
    public void update(Employee bo) {
        checkUsername(bo);
        employeeMapper.updateByPrimaryKeySelective(bo);
    }

    @Override
    public void deleteById(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<EmployeeVO> findAll() {
        return employeeMapper.findAll();
    }

    @Override
    public EmployeeVO findById(Long id) {
        return employeeMapper.findById(id);
    }

    /**
     * 检查用户名是否重复
     * @param bo
     */
    public void checkUsername(Employee bo) {
        if (!StringUtils.isEmpty(bo.getUsername())) {
            Long idInDb = employeeMapper.findByUsername(bo.getUsername());
            if (idInDb != null && !idInDb.equals(bo.getId())) {
                throw new SystemException("已经存在该用户名");
            }
        }
    }
}
